package com.stylefeng.guns.modular.borrowing.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.core.common.constant.factory.PageFactory;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.core.util.DateUtil;
import com.stylefeng.guns.modular.borrowing.model.Borrowing;
import com.stylefeng.guns.modular.borrowing.service.IBorrowingInfoService;
import com.stylefeng.guns.modular.borrowing.service.ICustomerinfoService;
import com.stylefeng.guns.modular.rate.service.IRateService;
import com.stylefeng.guns.modular.system.dao.BorrowingInfoMapper;
import com.stylefeng.guns.modular.system.model.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  应收应付服务实现类
 * </p>
 *
 * @author laoyu
 * @since 2018-07-04
 */
@Service
public class BorrowingInfoServiceImpl extends ServiceImpl<BorrowingInfoMapper, BorrowingInfo> implements IBorrowingInfoService {


    @Autowired
    private IRateService rateService;

    @Autowired
    private ICustomerinfoService customerinfoService;



    /**
     * 根据现金收支表插入应收应付往来数据
     * @param cashExpenditure
     */
    @Override
    public void insertBorrowing(String platform, CashExpenditure cashExpenditure)throws GunsException {
        BorrowingInfo lastBorrowingInfo = baseMapper.searchLast(platform);

        double lastBalance = 0;
        if (lastBorrowingInfo != null){
            lastBalance = lastBorrowingInfo.getBalance();
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
        String rateTime = simpleDateFormat.format(cashExpenditure.getRevDate());

        BorrowingInfo borrowingInfo = new BorrowingInfo();
        borrowingInfo.setOrderNumber(cashExpenditure.getOrderNumber());
        borrowingInfo.setPlatform(platform);
        borrowingInfo.setNote(cashExpenditure.getNote());
        borrowingInfo.setContact(cashExpenditure.getCustomer());
        borrowingInfo.setRevDate(cashExpenditure.getRevDate());
        if (cashExpenditure.getType().intValue()==CashExpenditure.Enum_Type.收入.value.intValue()){
            borrowingInfo.setPisoAmount(cashExpenditure.getMoney());
            borrowingInfo.setPisoToRmb(cashExpenditure.getMoney()/rateService.search(rateTime).getRate());
            //借款
            if (cashExpenditure.getDetailsId()==CashExpenditure.Enum_DetailTypes.应付.value){
                borrowingInfo.setType(BorrowingInfo.Enum_Type.应付.value);

            }
            borrowingInfo.setBalance(lastBalance-borrowingInfo.getPisoToRmb());

        }else if(cashExpenditure.getType().intValue()==CashExpenditure.Enum_Type.支出.value.intValue()) {
            borrowingInfo.setPisoAmount(cashExpenditure.getMoney());
            borrowingInfo.setPisoToRmb(cashExpenditure.getMoney()/rateService.search(rateTime).getRate());
            //还款
            if (cashExpenditure.getDetailsId()==CashExpenditure.Enum_DetailTypes.借出PS.value){
                borrowingInfo.setType(BorrowingInfo.Enum_Type.应收.value);
            }
            borrowingInfo.setBalance(lastBalance+borrowingInfo.getPisoToRmb());
        }
        borrowingInfo.setContact(cashExpenditure.getCustomer());
        borrowingInfo.setNote(cashExpenditure.getNote());
        borrowingInfo.setCreattime(new Date());
        borrowingInfo.setUpdatetime(new Date());

        this.insert(borrowingInfo);
    }

    /**
     * 描述:根据人民币银行收支表插入应收应付往来数据
     * 创建人: laoyu
     * 日期: 2018/7/29 0029
     * 时间: 下午 4:00
     */
    @Override
    public void insertBorrowing(String platform, RmbCashReceipts rmbCashReceipts) throws GunsException {

        BorrowingInfo lastBorrowingInfo = baseMapper.searchLast(platform);
        double lastBalance = 0;
        if (lastBorrowingInfo != null){
            lastBalance = lastBorrowingInfo.getBalance();
        }
        BorrowingInfo borrowingInfo = new BorrowingInfo();
        borrowingInfo.setOrderNumber(rmbCashReceipts.getOrderNumber());
        borrowingInfo.setPlatform(platform);
        borrowingInfo.setContact(rmbCashReceipts.getCustomer());
        borrowingInfo.setRevDate(rmbCashReceipts.getRevdate());
        if (RmbCashReceipts.Enum_Summary.应付.value.intValue()==rmbCashReceipts.getSummary()){
            if(rmbCashReceipts.getType()==RmbCashReceipts.Enum_Type.收款.value) {
                borrowingInfo.setRmbAmount(rmbCashReceipts.getAmount());
                borrowingInfo.setType(BorrowingInfo.Enum_Type.应付.value);
                borrowingInfo.setBalance(lastBalance-rmbCashReceipts.getAmount());
            }
        }else if (RmbCashReceipts.Enum_Summary.应收.value.intValue()==rmbCashReceipts.getSummary()){
            if (rmbCashReceipts.getType()==RmbCashReceipts.Enum_Type.支出.value){
                borrowingInfo.setRmbAmount(rmbCashReceipts.getAmount());
                borrowingInfo.setType(BorrowingInfo.Enum_Type.应收.value.intValue());
                borrowingInfo.setBalance(lastBalance+rmbCashReceipts.getAmount());
            }
        }
        borrowingInfo.setNote(rmbCashReceipts.getNote());
        borrowingInfo.setCreattime(new Date());
        borrowingInfo.setUpdatetime(new Date());

        this.insert(borrowingInfo);


    }

    /**
     * 描述:当piso现金借贷修改，则修改应的应收收据
     * 创建人: laoyu
     * 日期: 2018/7/30 0030
     * 时间: 下午 5:45
     */
    @Override
    public void update(CashExpenditure cashExpenditure, CashExpenditure oldCashExpenditure) throws GunsException {
        //g根据订单查找应收应付
        EntityWrapper<BorrowingInfo> wrapper = new EntityWrapper<BorrowingInfo>();
        wrapper.eq("platform",oldCashExpenditure.getPlatform());
        wrapper.eq("order_number",oldCashExpenditure.getOrderNumber());
        BorrowingInfo borrowingInfo = this.selectOne(wrapper);
        //查询当月的费率
        Rate rate = rateService.search(new SimpleDateFormat("yyyy-MM").format(borrowingInfo.getRevDate()));
        //计算修改差额
        double difference = 0;
        if (cashExpenditure.getType() == oldCashExpenditure.getType()) {
            if (cashExpenditure.getType().intValue() == CashExpenditure.Enum_Type.收入.value.intValue())
                difference = borrowingInfo.getPisoAmount() - cashExpenditure.getMoney();
            if (cashExpenditure.getType().intValue() == CashExpenditure.Enum_Type.支出.value.intValue())
                difference = cashExpenditure.getMoney() - borrowingInfo.getPisoAmount();

        }else {
            if (cashExpenditure.getType().intValue() == CashExpenditure.Enum_Type.收入.value.intValue()) {
                difference = -(borrowingInfo.getPisoAmount() + cashExpenditure.getMoney());
                if (cashExpenditure.getDetailsId()==CashExpenditure.Enum_DetailTypes.应付.value)
                    borrowingInfo.setType(BorrowingInfo.Enum_Type.应付.value);
            }
            if (cashExpenditure.getType().intValue() == CashExpenditure.Enum_Type.支出.value.intValue()) {
                difference = cashExpenditure.getMoney() + borrowingInfo.getPisoAmount();

                 if (cashExpenditure.getDetailsId() == CashExpenditure.Enum_DetailTypes.借出PS.value)
                    borrowingInfo.setType(BorrowingInfo.Enum_Type.应收.value);
            }
        }
        //修改当前期
        borrowingInfo.setPisoAmount(cashExpenditure.getMoney());
        borrowingInfo.setPisoToRmb(cashExpenditure.getMoney()/rate.getRate());
        borrowingInfo.setBalance(borrowingInfo.getBalance()+difference/rate.getRate());
        this.updateById(borrowingInfo);
        //修改当前之后的所有余额
        baseMapper.updateBalance(borrowingInfo.getPlatform(),borrowingInfo.getId(),difference/rate.getRate());

    }

    /**
     * 描述:修改应收应付
     * 创建人: laoyu
     * 日期: 2018/8/10 0010
     * 时间: 上午 9:42
     */
    @Override
    public void update(BorrowingInfo borrowingInfo, BorrowingInfo oldBorrowingInfo) throws GunsException {

        double difference = 0;//修改差额
        if (oldBorrowingInfo.getType()==borrowingInfo.getType()){//应收应付类型相同
            if (borrowingInfo.getType()==BorrowingInfo.Enum_Type.应收.value){
                difference = borrowingInfo.getRmbAmount()-oldBorrowingInfo.getRmbAmount();
            }else if (borrowingInfo.getType() == BorrowingInfo.Enum_Type.应付.value){
                difference = oldBorrowingInfo.getRmbAmount()-borrowingInfo.getRmbAmount();
            }
        }else {
            if (borrowingInfo.getType()==BorrowingInfo.Enum_Type.应收.value){
                difference =  borrowingInfo.getRmbAmount()+oldBorrowingInfo.getRmbAmount();
            }else if (borrowingInfo.getType() == BorrowingInfo.Enum_Type.应付.value){
                difference = -oldBorrowingInfo.getRmbAmount()-borrowingInfo.getRmbAmount();
            }

        }
        //修改当期应收应付
        borrowingInfo.setUpdatetime(new Date());
        baseMapper.updateById(borrowingInfo);
        //修改当期和之后的余额
        baseMapper.updateBalance(ShiroKit.getUser().getDeptcode(),borrowingInfo.getId(),difference);

    }

    /**
     * 描述:当rmb银行借贷修改，则修改应的应收收据
     * 创建人: laoyu
     * 日期: 2018/7/30 0030
     * 时间: 下午 5:45
     */
    @Override
    public void update(RmbCashReceipts rmbCashReceipts, RmbCashReceipts oldRmbCashReceipts) throws GunsException {

        //g根据订单查找应收应付
        EntityWrapper<BorrowingInfo> wrapper = new EntityWrapper<BorrowingInfo>();
        wrapper.eq("platform",oldRmbCashReceipts.getPlatform());
        wrapper.eq("order_number",rmbCashReceipts.getOrderNumber());
        BorrowingInfo borrowingInfo = this.selectOne(wrapper);
        //计算修改差额
        double difference = 0;
        if (rmbCashReceipts.getType()==RmbCashReceipts.Enum_Type.收款.value) {
            difference = borrowingInfo.getPisoToRmb() - rmbCashReceipts.getAmount();
            borrowingInfo.setPisoToRmb(rmbCashReceipts.getAmount());
            borrowingInfo.setRmbAmount(rmbCashReceipts.getAmount());

        }
        if (rmbCashReceipts.getType()==RmbCashReceipts.Enum_Type.支出.value) {
            difference = rmbCashReceipts.getAmount() - borrowingInfo.getPisoToRmb()  ;
            borrowingInfo.setPisoToRmb(rmbCashReceipts.getAmount());
            borrowingInfo.setRmbAmount(rmbCashReceipts.getAmount());

        }
        //修改当前期
        this.updateById(borrowingInfo);
        //修改当前之后的所有余额
        baseMapper.updateBalance(borrowingInfo.getPlatform(),borrowingInfo.getId(),difference);

    }

    /**
     * 描述:下载应收应付表格
     * 创建人: laoyu
     * 日期: 2018/8/6 0006
     * 时间: 下午 5:14
     */
    @Override
    public Map<String, Object> load(List<BorrowingInfo> borrowingInfos, String platform,String beginDate,String endDate) throws GunsException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Map<String,Object> resultMap = new HashMap<>();
        List<Map<String,Object>> borrwMapList = new ArrayList<>();
        //组装数据
        double loanPisoTotal = 0;
        double loanPisoToRmbTotal = 0;
        double loanRMBTotal = 0;
        double repPisoTotal = 0;
        double repPisoToRmbTotal = 0;
        double repRMBTotal = 0;
        for (BorrowingInfo borrowingInfo : borrowingInfos){
            Map<String,Object> loadMap = new HashMap<>();
            loadMap.put("revDate",simpleDateFormat.format(borrowingInfo.getRevDate()));
            loadMap.put("contact",borrowingInfo.getContact());
            loadMap.put("summary",BorrowingInfo.getType(borrowingInfo.getType()));
            loadMap.put("balance",borrowingInfo.getBalance());
            loadMap.put("note",borrowingInfo.getNote());
            if (borrowingInfo.getType()==BorrowingInfo.Enum_Type.应收.value) {
                loadMap.put("loanPiso", borrowingInfo.getPisoAmount());
                loadMap.put("loanPisoToRmb", borrowingInfo.getPisoToRmb());
                loadMap.put("loanRMB", borrowingInfo.getRmbAmount());
                loadMap.put("repPiso", 0);
                loadMap.put("repPisoToRmb", 0);
                loadMap.put("repRMB", 0);
            }else {
                loadMap.put("loanPiso", 0);
                loadMap.put("loanPisoToRmb", 0);
                loadMap.put("loanRMB", 0);
                loadMap.put("repPiso", borrowingInfo.getPisoAmount());
                loadMap.put("repPisoToRmb", borrowingInfo.getPisoToRmb());
                loadMap.put("repRMB", borrowingInfo.getRmbAmount());
            }
            loanPisoTotal += borrowingInfo.getPisoAmount();
            loanPisoToRmbTotal +=borrowingInfo.getPisoToRmb();
            loanRMBTotal +=borrowingInfo.getRmbAmount();
            repPisoTotal +=borrowingInfo.getPisoAmount();
            repPisoToRmbTotal +=borrowingInfo.getPisoToRmb();
            repRMBTotal +=borrowingInfo.getRmbAmount();
            borrwMapList.add(loadMap);
        }

        resultMap.put("borrwMapList",borrwMapList);
        resultMap.put("loanPisoTotal",loanPisoTotal);
        resultMap.put("loanPisoToRmbTotal",loanPisoToRmbTotal);
        resultMap.put("loanRMBTotal",loanRMBTotal);
        resultMap.put("repPisoTotal",repPisoTotal);
        resultMap.put("repPisoToRmbTotal",repPisoToRmbTotal);
        resultMap.put("repRMBTotal",repRMBTotal);
        resultMap.put("name",platform.toUpperCase()+"应付/应收款项明细余额表");
        resultMap.put("platform",platform);
        resultMap.put("time",beginDate+"--"+endDate);

        return resultMap;
    }

    /**
     * 描述:获取应收应付汇总表
     * 创建人: laoyu
     * 日期: 2018/8/7 0007
     * 时间: 上午 11:24
     */
    @Override
    public List<Borrowing> getBorrowing(String contact,String platform,String beginDate,String endDate) throws GunsException {
        //查询平台的应收应付客户
        EntityWrapper<Customerinfo> customerinfoEntityWrapper = new EntityWrapper<Customerinfo>();
        customerinfoEntityWrapper.eq("platform",platform);
        //根据往来客户查询应收应付明细
        List<Customerinfo> customerinfos = customerinfoService.selectList(customerinfoEntityWrapper);
        List<Borrowing> borrowingList = new ArrayList<>();
        for (Customerinfo customerinfo: customerinfos){
            double lastBalance= 0;//上期余额
            double lastLoanPTR=0;//历史披索转人民币
            double lastRmb = 0;//历史人民币
            double loanPISO=0;//借款piso
            double loanPISOtORMB=0;//借款
            double loanRMB=0;//借款rmb
            double repPISO=0;//还款
            double repPISOToRMB=0;
            double repRMB=0;
            //查询对应往来客户的历史往来明细计算余额
            EntityWrapper<BorrowingInfo> borrowingInfoEntityWrapper = new EntityWrapper<>();
            borrowingInfoEntityWrapper.eq("platform",platform);
            borrowingInfoEntityWrapper.eq("contact",customerinfo.getCustomercode());
            borrowingInfoEntityWrapper.lt("rev_date",beginDate);
            List<BorrowingInfo> borrowingInfoHistorys = this.selectList(borrowingInfoEntityWrapper);
            for (BorrowingInfo borrowingInfo : borrowingInfoHistorys){
                if (borrowingInfo.getType()==BorrowingInfo.Enum_Type.应收.value) {
                    lastLoanPTR += borrowingInfo.getPisoToRmb();
                    lastRmb += borrowingInfo.getRmbAmount();
                }else {
                    lastLoanPTR -= borrowingInfo.getPisoToRmb();
                    lastRmb -= borrowingInfo.getRmbAmount();
                }
            }
            lastBalance = lastLoanPTR+lastRmb;
            List<BorrowingInfo> borrowingInfos = this.selectList(new EntityWrapper<BorrowingInfo>()
            .ge("rev_date", beginDate)
            .le("rev_date", endDate)
            .eq("platform",platform)
            .eq("contact",customerinfo.getCustomercode())
            .orderBy("rev_date",false)
            );
            if (borrowingInfos==null || borrowingInfos.size()==0) continue;
            Borrowing borrowing = new Borrowing();
            borrowing.setCustor(customerinfo.getCustomername());
            for (BorrowingInfo borrowingInfo : borrowingInfos){
                if (borrowingInfo.getType()==BorrowingInfo.Enum_Type.应收.value) {
                    loanPISO += borrowingInfo.getPisoAmount();
                    loanPISOtORMB += borrowingInfo.getPisoToRmb();
                    loanRMB += borrowingInfo.getRmbAmount();
                }else {
                    repPISO += borrowingInfo.getPisoAmount();
                    repPISOToRMB += borrowingInfo.getPisoToRmb();
                    repRMB += borrowingInfo.getRmbAmount();
                }
            }
            borrowing.setLastBalance(lastBalance);
            borrowing.setLoanPISO(loanPISO);
            borrowing.setLoanPISOtORMB(loanPISOtORMB);
            borrowing.setLoanRMB(loanRMB);
            borrowing.setLoanTotal(loanPISOtORMB+loanRMB);
            borrowing.setRepPISO(repPISO);
            borrowing.setRepPISOToRMB(repPISOToRMB);
            borrowing.setRepRMB(repRMB);
            borrowing.setRepTotal(repPISOToRMB+repRMB);
            borrowing.setBalance(loanPISOtORMB+loanRMB+lastBalance-repPISOToRMB-repRMB);
            borrowingList.add(borrowing);
        }
        return borrowingList;
    }

    /**
     * 描述:统计应付应收汇总表
     * 创建人: laoyu
     * 日期: 2018/8/11 0011
     * 时间: 下午 3:16
     */
    @Override
    public Map<String,Object> getBorrowingTotal(EntityWrapper<BorrowingInfo> wrapper, String platform, String beginDate)
            throws GunsException {

        Map<String,Object> tatol= new HashMap<String,Object>();
        tatol.put("incomePiso",0.00);
        tatol.put("incomePTR",0.00);
        tatol.put("incomeRMB",0.00);
        tatol.put("outPiso",0.00);
        tatol.put("outPTR",0.00);
        tatol.put("outRMB",0.00);
      /*  EntityWrapper<BorrowingInfo> wrapper = new EntityWrapper<BorrowingInfo>();
        wrapper.setSqlSelect("SUM(rmb_amount) AS rmbAmount,SUM(piso_to_rmb) AS pisoToRmb, SUM(piso_amount) AS pisoAmount , type");
        wrapper.eq("platform",platform);
        wrapper.ge("rev_date",beginDate);
        wrapper.le("rev_date",endDate);
        wrapper.groupBy("type");
        if(type!=null){
            wrapper.eq("type",type);
        }
        List<BorrowingInfo> tatolObjs=this.selectList(wrapper);
        for(BorrowingInfo obj:tatolObjs){
            if(obj.getType()!=null) {
                if (obj.getType().intValue() == BorrowingInfo.Enum_Type.应收.value.intValue()) {
                    tatol.put("incomePiso", obj.getPisoAmount());
                    tatol.put("incomePTR", obj.getPisoToRmb());
                    tatol.put("incomeRMB", obj.getRmbAmount());
                }
                if (obj.getType().intValue() == BorrowingInfo.Enum_Type.应付.value.intValue()) {
                    tatol.put("outPiso", obj.getPisoAmount());
                    tatol.put("outPTR", obj.getPisoToRmb());
                    tatol.put("outRMB", obj.getRmbAmount());
                }
            }
        }
        //获取余额
        wrapper = new EntityWrapper<BorrowingInfo>();
        wrapper.setSqlSelect("IFNULL(balance,0) as balance");
        wrapper.eq("platform", platform);
        wrapper.ge("rev_date",beginDate);
        wrapper.le("rev_date",endDate);
        wrapper.orderBy("id DESC");
        wrapper.last("LIMIT 1");
        if(type!=null){
            wrapper.eq("type",type);
        }
        BorrowingInfo balance=this.selectOne(wrapper);
        if(balance==null){
            tatol.put("amount",0.00);
        }else {
            tatol.put("amount",balance.getBalance());
        }*/

        return tatol;
    }

    /**
     * 描述:下载应收应付明细余额汇总
     * 创建人: laoyu
     * 日期: 2018/8/8 0008
     * 时间: 上午 10:00
     */
    @Override
    public Map<String, Object> loadBorrowing(EntityWrapper<BorrowingInfo> wrapper, String platform, String beginDate,
                                             String endDate) throws GunsException {


        wrapper.eq("platform",platform);
        //查询平台的应收应付客户
        EntityWrapper<Customerinfo> customerinfoEntityWrapper = new EntityWrapper<Customerinfo>();
        customerinfoEntityWrapper.eq("platform",platform);
        //根据往来客户查询应收应付明细
        List<Customerinfo> customerinfos = customerinfoService.selectList(customerinfoEntityWrapper);
        List<Map<String,Object>> borrowingList = new ArrayList<>();
        double loanPISOAll=0;
        double loanPISOtORMBAll=0;
        double loanRMBAll=0;
        double repPISOAll=0;
        double repPISOToRMBAll=0;
        double repRMBAll=0;
        for (Customerinfo customerinfo: customerinfos){
            double lastBalance= 0;//上期余额
            double lastLoanPTR=0;//历史披索转人民币
            double lastRmb = 0;//历史人民币
            double loanPISO=0;//借款piso
            double loanPISOtORMB=0;//借款
            double loanRMB=0;//借款rmb
            double repPISO=0;//还款
            double repPISOToRMB=0;
            double repRMB=0;

            //查询对应往来客户的历史往来明细计算余额
            EntityWrapper<BorrowingInfo> borrowingInfoEntityWrapper = new EntityWrapper<>();
            borrowingInfoEntityWrapper.eq("platform",platform);
            borrowingInfoEntityWrapper.eq("contact",platform);
            borrowingInfoEntityWrapper.lt("rev_date",beginDate);
            List<BorrowingInfo> borrowingInfoHistorys = this.selectList(borrowingInfoEntityWrapper);
            for (BorrowingInfo borrowingInfo : borrowingInfoHistorys){
                if (borrowingInfo.getType()==BorrowingInfo.Enum_Type.应收.value) {
                    lastLoanPTR += borrowingInfo.getPisoToRmb();
                    lastRmb += borrowingInfo.getRmbAmount();
                }else {
                    lastLoanPTR -= borrowingInfo.getPisoToRmb();
                    lastRmb -= borrowingInfo.getRmbAmount();
                }
            }
            lastBalance = lastLoanPTR+lastRmb;
            wrapper.eq("contact",customerinfo.getCustomercode());
            List<BorrowingInfo> borrowingInfos = this.selectList(wrapper);
            if (borrowingInfos == null) continue;
            Map<String,Object> borrowing = new HashMap<>();

            for (BorrowingInfo borrowingInfo : borrowingInfos){
                if (borrowingInfo.getType()==BorrowingInfo.Enum_Type.应收.value) {
                    loanPISO += borrowingInfo.getPisoAmount();
                    loanPISOtORMB += borrowingInfo.getPisoToRmb();
                    loanRMB += borrowingInfo.getRmbAmount();
                }else {
                    repPISO += borrowingInfo.getPisoAmount();
                    repPISOToRMB += borrowingInfo.getPisoToRmb();
                    repRMB += borrowingInfo.getRmbAmount();
                }
            }
            loanPISOAll += loanPISO;
            loanPISOtORMBAll += loanPISOtORMB;
            loanRMBAll += loanRMB;
            repPISOAll += repPISO;
            repPISOToRMBAll += repPISOToRMB;
            repRMBAll += repRMB;
            borrowing.put("custor",customerinfo.getCustomername());
            borrowing.put("lastBalance",lastBalance);
            borrowing.put("loanPISO",loanPISO);
            borrowing.put("loanPISOtORMB",loanPISOtORMB);
            borrowing.put("loanRMB",loanRMB);
            borrowing.put("loanTotal",loanPISOtORMB+loanRMB);
            borrowing.put("repPISO",repPISO);
            borrowing.put("repPISOToRMB",repPISOToRMB);
            borrowing.put("repRMB",repRMB);
            borrowing.put("repTotal",repPISOToRMB+repRMB);
            borrowing.put("balance",loanPISOtORMB+loanRMB+lastBalance-repPISOToRMB-repRMB);
            borrowingList.add(borrowing);
        }
        Map<String,Object> loadMap = new HashMap<>();
        loadMap.put("borrowingList",borrowingList);
        loadMap.put("name",platform.toUpperCase()+"应付/应收款项明细余额汇总表");
        loadMap.put("platform",platform.toUpperCase());
        loadMap.put("time",beginDate+"---"+endDate);
        loadMap.put("loanPISOAll",loanPISOAll);
        loadMap.put("loanPISOtORMBAll",loanPISOtORMBAll);
        loadMap.put("loanRMBAll",loanRMBAll);
        loadMap.put("loanAll",loanRMBAll+loanPISOtORMBAll);
        loadMap.put("repPISOAll",repPISOAll);
        loadMap.put("repPISOToRMBAll",repPISOToRMBAll);
        loadMap.put("repRMBAll",repRMBAll);
        loadMap.put("repAll",repRMBAll+repPISOToRMBAll);

        return loadMap;
    }


    /**
     * 描述:合计
     * 创建人: xiang
     * 日期: 2018/8/9
     * 时间: 11:05
     */
    @Override
    public Map<String,Object> tatol(Integer type,String beginDate, String  endDate,String platform){
        Map<String,Object> tatol= new HashMap<String,Object>();
        tatol.put("incomePiso",0.00);
        tatol.put("incomePTR",0.00);
        tatol.put("incomeRMB",0.00);
        tatol.put("outPiso",0.00);
        tatol.put("outPTR",0.00);
        tatol.put("outRMB",0.00);
        EntityWrapper<BorrowingInfo> wrapper = new EntityWrapper<BorrowingInfo>();
        wrapper.setSqlSelect("SUM(rmb_amount) AS rmbAmount,SUM(piso_to_rmb) AS pisoToRmb, SUM(piso_amount) AS pisoAmount , type");
        wrapper.eq("platform",platform);
        wrapper.ge("rev_date",beginDate);
        wrapper.le("rev_date",endDate);
        wrapper.groupBy("type");
        if(type!=null){
            wrapper.eq("type",type);
        }
        List<BorrowingInfo> tatolObjs=this.selectList(wrapper);
        for(BorrowingInfo obj:tatolObjs){
            if(obj.getType()!=null) {
                if (obj.getType().intValue() == BorrowingInfo.Enum_Type.应收.value.intValue()) {
                    tatol.put("incomePiso", obj.getPisoAmount());
                    tatol.put("incomePTR", obj.getPisoToRmb());
                    tatol.put("incomeRMB", obj.getRmbAmount());
                }
                if (obj.getType().intValue() == BorrowingInfo.Enum_Type.应付.value.intValue()) {
                    tatol.put("outPiso", obj.getPisoAmount());
                    tatol.put("outPTR", obj.getPisoToRmb());
                    tatol.put("outRMB", obj.getRmbAmount());
                }
            }
        }
        //获取余额
        wrapper = new EntityWrapper<BorrowingInfo>();
        wrapper.setSqlSelect("IFNULL(balance,0) as balance");
        wrapper.eq("platform", platform);
        wrapper.ge("rev_date",beginDate);
        wrapper.le("rev_date",endDate);
        wrapper.orderBy("id DESC");
        wrapper.last("LIMIT 1");
        if(type!=null){
            wrapper.eq("type",type);
        }
        BorrowingInfo balance=this.selectOne(wrapper);
        if(balance==null){
            tatol.put("amount",0.00);
        }else {
            tatol.put("amount",balance.getBalance());
        }

        return tatol;

    }

    /**
     * 描述:删除应收应付
     * 创建人: laoyu
     * 日期: 2018/8/9 0009
     * 时间: 下午 5:07
     */
    @Override
    public void delete(String platform, String orderNumber) throws GunsException {
        EntityWrapper<BorrowingInfo> wrapper = new EntityWrapper<>();
        wrapper.eq("platform",platform);
        wrapper.eq("order_number",orderNumber);
        List<BorrowingInfo> borrowingInfoList= baseMapper.selectList(wrapper);
        if (borrowingInfoList.isEmpty()){
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR,"没有查询到对应的应收应付报表");
        }
        baseMapper.delete(wrapper);
        //修改删除订单之后的所有报表余额
        BorrowingInfo borrowingInfo = borrowingInfoList.get(0);
        double difference = 0;//修改差额
        if (borrowingInfo.getType()==BorrowingInfo.Enum_Type.应收.value)
            difference = -borrowingInfo.getRmbAmount();
        if (borrowingInfo.getType()==BorrowingInfo.Enum_Type.应付.value)
            difference = borrowingInfo.getRmbAmount();
        baseMapper.updateBalance(borrowingInfo.getPlatform(),borrowingInfo.getId(),difference);

    }


    /**
     * 描述:获取应付应收明细
     * 创建人: laoyu
     * 日期: 2018/8/16 0016
     * 时间: 下午 2:07
     */
    @Override
    public List<BorrowingInfo> search(String platform, Integer type, String beginDate, String endDate, String contact) {
        //分页查询
        Page<BorrowingInfo> page = new PageFactory<BorrowingInfo>().defaultPage();
        //组装查询
        EntityWrapper<BorrowingInfo> wrapper = new EntityWrapper<BorrowingInfo>();
        wrapper.eq("platform",platform);
        //组装查询条件
        if(StringUtils.isNotBlank(beginDate)) {
            wrapper.ge("rev_date", beginDate);
        }else{
            wrapper.ge("rev_date", DateUtil.today(0));
        }
        if(StringUtils.isNotBlank(endDate)) {
            wrapper.le("rev_date", endDate);
        }else{
            wrapper.le("rev_date", DateUtil.today(1));
        }
        if(type!=null){
            wrapper.eq("type", type);
        }
        if (StringUtils.isNotBlank(contact))
            wrapper.eq("contact",contact);
        wrapper.orderBy("rev_date",false);

        List<BorrowingInfo> borrowingInfoList=baseMapper.selectPage(page,wrapper);
        if (borrowingInfoList.isEmpty()){
            //查询开始时间之前的的最后一笔余额
            EntityWrapper<BorrowingInfo> borrowingInfoEntityWrapper = new EntityWrapper<>();
            borrowingInfoEntityWrapper.ge("platform",platform);
            borrowingInfoEntityWrapper.lt("rev_date",beginDate);
            borrowingInfoEntityWrapper.orderBy("id",false);
            borrowingInfoEntityWrapper.last(" limit 1");
            BorrowingInfo lastBorrow = baseMapper.selectList(borrowingInfoEntityWrapper).get(0);
            //将最后的余额加到数据中
            BorrowingInfo borrowingInfo = new BorrowingInfo();
            borrowingInfo.setBalance(lastBorrow.getBalance());
            borrowingInfoList.add(borrowingInfo);
        }


        return borrowingInfoList;
    }



    /**
     * 描述:添加应收应付
     * 创建人: laoyu
     * 日期: 2018/8/16 0016
     * 时间: 下午 3:56
     */
    @Override
    public void sav(BorrowingInfo borrowingInfo) {
            BorrowingInfo lastBorrow = baseMapper.searchLast(borrowingInfo.getPlatform());
            Rate rate = rateService.search(new SimpleDateFormat("yyyy-MM").format(borrowingInfo.getRevDate()));
        if (borrowingInfo.getType()==BorrowingInfo.Enum_Type.应收.value)
            borrowingInfo.setBalance(lastBorrow.getBalance()+borrowingInfo.getRmbAmount()+borrowingInfo.getPisoAmount()/rate.getRate());
        else
            borrowingInfo.setBalance(lastBorrow.getBalance()-borrowingInfo.getRmbAmount()-borrowingInfo.getPisoAmount()/rate.getRate());

        baseMapper.insert(borrowingInfo);

    }
}
